import React from 'react'
import {getToken} from 'utils/authority'
import {Player} from 'video-react'
import './index.less'
import './video.less'
import {Button, message} from 'antd'
import axios from 'axios'
import {connect} from 'dva'
import {toEmotion} from 'utils'
import Modal from './Modal'

@connect(({discover, employee, loading}) => ({
  discover,
  employee,
  loading: loading.effects['discover/query'],
}))
export default class FriendCircle extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      circleInfo: [],
      isLoadingMore: false,
      total: '',
      text: '加载更多',
      current: 1,
      size: 10,
    }
  }


  componentDidMount (props) {
    const {discover} = this.props
    const {author} = discover
    const snsId = author.snsId ? author.snsId : ''
    axios.get('/api/friendCircle/customer/' + author.id + '?current=' + this.state.current + "&startTime=" + author.startTime + "&snsId=" + snsId + '&size=' + this.state.size, {headers: {'Authentication': getToken()}})

      .then(res => {
        this.setState({
          circleInfo: res.data.data.records,
          total: res.data.data.total,
        })
        if (res.data.data.records.length < 10) {
          this.setState({
            text: '没有更多数据了',
          })
        }
      })
  }

  downInit = () => {
    const target = this
    const wrapper = this.refs.wrapper
    const loadMoreDataFn = this.loadMoreDataFn

    function callback () {
      const top = wrapper.getBoundingClientRect().top + 950
      const windowHeight = document.getElementById('detail').clientHeight
      if (top && top < windowHeight) {
        loadMoreDataFn(target)
      }
    }

    callback()
  }

  loadMoreDataFn = (target) => {
    if (target.state.current * target.state.size < target.state.total) {
      const {discover: {author = {}}} = target.props
      let current = target.state.current
      let size = target.state.size
      current += 1
      target.setState({
        current: current,
      })
      const snsId = author.snsId ? author.snsId : ''
      axios.get('/api/friendCircle/customer/' + author.id + '?current=' + current + "&startTime=" + author.startTime + "&snsId=" + snsId + '&size=' + size, {headers: {'Authentication': getToken()}})
        .then(res => {
          res.data.data.records.forEach(element => {
            target.setState({
              circleInfo: target.state.circleInfo.concat(element),
              text: '加载更多',
            })
          })
        })
    } else {
      target.setState({
        text: '没有更多数据了',
      })
    }
  }

  hideDiscoveries () {
    const {dispatch} = this.props
    dispatch({
      type: 'discover/hideDiscoveries',
    })
  }

  showModal = (item) => {
    const {dispatch} = this.props
    dispatch({
      type: "employee/query",
      payload: {current: 1, size: 10},
    })
    dispatch({
      type: "employee/updateState",
      payload: {
        modalVisible: true,
      },
    })
    dispatch({
      type: 'discover/updateState',
      payload: {
        recommendItem: item
      }
    })
  }

  render () {
    const {
      discover: {author = {}, recommendItem},
      requireRecommend = false,
      dispatch,
      employee: {
        list, departments, roles,
        pagination, modalVisible,
        selectedRowKeys, selectedRows,
      },
    } = this.props

    const modalProps = {
      visible: modalVisible,
      title: '优质朋友圈',
      list,
      departments,
      roles,
      pagination,
      onChange (page) {
        dispatch({
          type: "employee/query",
          payload: {
            current: page.current,
            size: page.pageSize,
          },
        })
      },
      handleSearch (data) {
        if (data) {
          dispatch({
            type: "employee/query",
            payload: {
              ...data,
              current: 1,
              size: 10,
            },
          })
        } else {
          dispatch({
            type: "employee/query",
          })
        }
      },
      showModal: this.showModal,
      handleCancel () {
        dispatch({
          type: "employee/updateState",
          payload: {
            modalVisible: false,
            selectedRowKeys: [],
          },
        })
      },
      rowSelection: {
        selectedRowKeys,
        onChange: (keys, selectedRows) => {
          dispatch({
            type: 'employee/updateState',
            payload: {
              selectedRowKeys: keys,
              selectedRows: selectedRows,
            },
          })
        },
      },
      handleOk (fields) {
        if (selectedRows.length <= 0) {
          message.error("请至少选择一位员工查看权限")
          return
        }

        const data = {
          type: 0,
          friendCircleId: recommendItem['id'],
          description: fields['description'],
          empId: selectedRows.map(item => Number(item.id))
        }

        dispatch({
          type: 'highQualityFriendCircle/create',
          payload: data
        }).then(() => {
          dispatch({
            type: "employee/updateState",
            payload: {
              modalVisible: false,
              selectedRowKeys: [],
              selectedRows: [],
              currentItem: {},
            },
          })
        })
      },
    }

    return <div className="container-discoveries" onScroll={() => {
      this.downInit()
    }}>
      <div id="window-container" className="window" style={{maxHeight: 800}}>
        {/*<div className="switch">
            简洁模式：
            <span className="ivu-switch">
              <span className="ivu-switch-inner">
                <span>关</span>
              </span>
            </span>
           </div> */}
        <div id="scrollLoader-container" className="container-main" style={{maxHeight: 800}}>
          <div style={{minHeight: 748, overflowX: 'hidden'}}>
            <div className="title">
              <p>{author.name || author.dfriendId}的朋友圈</p>
            </div>
            <div className="header">
              <div className="cover">
                <img src={author.background} width="100%"/>
              </div>
              <div className="load">
                <div className="loadName">
                  <span>{author.name || author.dfriendId}</span>
                </div>
                <button className="loadHeader imagePreview" style={{
                  backgroundImage: 'url("' + author.avatar + '")',
                  backgroundSize: '100%',
                  backgroundRepeat: 'no-repeat',
                }}/>
              </div>
              <div className="sign">
                <span>{author.signature}</span>
              </div>
            </div>
            <div id='detail'>
              {this.state.circleInfo.length && this.state.circleInfo.length > 0 ? (<div className="detail">
                {this.state.circleInfo.map((v, index) => {
                  return (
                    <div className="line an-move-left" key={index}>
                      <div className="pean">
                        <div className="header" style={{
                          borderRadius: '3px 3px 3px 3px',
                          backgroundImage: 'url("' + author.avatar + '")',
                        }}/>
                        <div className="info">
                          <div className="name">
                            <span><strong>{author.name || author.dfriendId}</strong></span>
                            {/*<button className="ivu-btn ivu-btn-primary ivu-btn-circle ivu-btn-small delerecommend"*/}
                            {/*id="button_0">*/}
                            {/*<span>推荐</span>*/}
                            {/*</button>*/}
                            {requireRecommend &&
                            <div style={{
                              float: "right",
                            }}>
                              <Button disabled={v.recommend} type={'primary'} size={'small'}
                                      style={{height: '19px', padding: '0 4px'}}
                                      onClick={() => this.showModal(v)}>{v.recommend ? '已推荐' : '推荐'}</Button>
                            </div>
                            }
                          </div>
                          <div className="text">
                            <span>
                              {v.type === 0 ? (
                                <div>
                                  <div dangerouslySetInnerHTML={{__html: toEmotion(v.content)}}/>
                                  <div>
                                    {v.images.map((item, index) => {
                                      return (
                                        <div key={index} className="img-li" style={{
                                          display: 'inline-block',
                                          marginRight: '3px',
                                          width: '32.3%',
                                          marginBottom: '-3px',
                                        }}>
                                          <div className="imagePreview download-jpg">
                                            <div className="discover-img"
                                                 style={{backgroundImage: 'url("' + item + '")'}}/>
                                          </div>
                                        </div>
                                      )
                                    })}
                                  </div>
                                </div>
                              ) : null}
                              {
                                v.type === 1 ?
                                  (
                                    <div>
                                      <div dangerouslySetInnerHTML={{__html: toEmotion(v.content)}}/>
                                      <div className="link">
                                        <div className="LArea">
                                          <div className="LImage">
                                            {v.share ? (<img src={v.share.icon} className="link-img"/>) : null}
                                          </div>
                                          <div className="LText">
                                            <div className="LTextValign">
                                              <a target="_blank" style={{color: 'black'}}
                                                 href={v.share ? v.share.url || (v.share.subtitle.startsWith("http") && v.share.subtitle) : '#'}>
                                                {v.share ? (<div>{v.share.title}</div>) : null}
                                              </a>
                                            </div>
                                          </div>
                                        </div>
                                      </div>
                                    </div>
                                  ) : null
                              }
                              {
                                v.type === 2 ? (
                                  <div>
                                    <div dangerouslySetInnerHTML={{__html: toEmotion(v.content)}}/>
                                    {v.images.map((item, index) => {
                                      return (
                                        <div key={index} className="img-li" style={{
                                          display: 'inline-block',
                                          marginRight: '3px',
                                          width: '32.3%',
                                          marginBottom: '-3px',
                                        }}>
                                          <div className="imagePreview download-jpg">
                                            <div className="discover-img"
                                                 style={{backgroundImage: 'url("' + item + '")'}}/>
                                          </div>
                                        </div>
                                      )
                                    })}
                                  </div>
                                ) : null
                              }
                              {
                                v.type === 3 ? (
                                  <div>
                                    <div dangerouslySetInnerHTML={{__html: toEmotion(v.content)}}/>
                                    <Player src={v.video}/>
                                  </div>
                                ) : null
                              }
                            </span>
                          </div>
                          <div>
                            <div className="position">{v.location}</div>
                            <div className="time">
                              <span>{v.time}</span>
                              <button className="timeIcon icon setCommont"/>
                            </div>
                            {v.comments.length != 0 ? (
                              <div className="comment">
                                <div className="triangleIcon"/>
                                <div className="CComment">
                                  <a href="#"/>
                                  {v.comments.map((items, index) => {
                                    if (items.to) {
                                      return (
                                        <div className="CArea" key={index}>
                                          <div className="CAreaSpan CAreaName inline">{items.from}<span
                                            style={{color: '#000'}}>回复</span>{items.to}
                                          </div>
                                          <span className="CAreaSpan">:&nbsp;</span>
                                          <span className="CAreaText CAreaSpan">
                                          <span>{items.text}</span>
                                        </span>
                                        </div>
                                      )
                                    } else {
                                      return (
                                        <div className="CArea" key={index}>
                                          <span className="CAreaSpan CAreaName">{items.from}</span>
                                          <span className="CAreaSpan">:&nbsp;</span>
                                          <span className="CAreaText CAreaSpan">
                                          <span>{items.text}</span>
                                        </span>
                                        </div>
                                      )
                                    }
                                  })}
                                </div>
                              </div>
                            ) : null}
                          </div>
                        </div>
                      </div>
                    </div>
                  )
                })}
              </div>) : <div style={{fontSize: '30px', textAlign: 'center', marginTop: '80px'}}>数据加载中</div>}
            </div>
            <div className="loadMore" ref="wrapper"
                 onClick={this.loadMoreDataFn.bind(this, this)}>{this.state.text}</div>
          </div>
        </div>
      </div>
      < div className="shadow-discoveries" onClick={() => this.hideDiscoveries()}/>
      <Modal {...modalProps}/>
    </div>
  }
}
